<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :show-before="true">
        <span slot="before">共{{ page.total }}条数据</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="warning" @click="exportExel">导出</el-button>
          <el-button icon="plus" type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>

      </PageTools>
      <!-- 放置表格和分页 -->
      <el-card v-loading="loading">
        <el-table border :data="list">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="图片">
            <template #default="{row}">
              <img v-imgerr="require('../../assets/common/head.jpg')" class="avatar" :src="row.staffPhoto" alt="" @click="showAvatar(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formtEmp" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template #default="{row}">
              {{ row.timeOfEntry|formatDate }}
            </template>
          </el-table-column>

          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template #default="{row}">
              <el-switch
                :value="row.enableState===1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">

                查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assignRole(row.id)">角色</el-button>
              <el-button :disabled="!checkPerm('delEmployee')" type="text" size="small" @click="deleteEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :page-size="page.size"
            :current-page="page.page"
            :total="page.total"
            @current-change="changePage"
          />
        </el-row>
      </el-card>
      <AddEmployee :show-dialog.sync="showDialog" />
      <el-dialog title="头像" :visible.sync="isShowAvatar">
        <el-row type="flex" justify="center">
          <canvas ref="avatarQRCode" />
        </el-row>
      </el-dialog>
    </div>
    <!-- 角色弹窗 -->
    <ROle ref="assignRole" :dialog-visible.sync="dialogVisible" :employee-id="employeeId" />
  </div>
</template>

<script>
// import PageTools from '@/components/pageTools/index.vue'
import { getcomplyi, delEmployee } from '@/api/employees'
import EnumEmployou from '@/api/constant/employees'
// import { export_json_to_excel } from '@/vendor/Export2Excel'
import { formatDate } from '@/filters'
import AddEmployee from './components/add-employee.vue'
// console.log(EnumEmployou)
import ROle from './components/role.vue'
import QRCode from 'qrcode'
// import { checkPermMixin } from '@/mixin'
export default {
  // components: {
  //   PageTools
  // },
  components: {
    AddEmployee,
    ROle
  },
  data() {
    return {
      employeeId: '',
      dialogVisible: false,
      imgUrl: '',
      showDialog: false,
      isShowAvatar: false,
      loading: false,
      list: [], // 接数据的
      page: {
        page: 1, // 当前页码
        size: 5,
        total: 0 // 总数
      }

    }
  },
  created() {
    this.getcomply()
  },
  methods: {

    assignRole(id) {
      // 传一个id给到自组件的方法
      this.$refs.assignRole.getUserDetail(id)
      this.employeeId = id
      // 把弹框显示出来
      this.dialogVisible = true
    },
    showAvatar(imgUrl) {
      if (imgUrl) {
        this.isShowAvatar = true
        this.$nextTick(() => {
          QRCode.toCanvas(this.$refs.avatarQRCode, imgUrl, {
            width: 300,
            color: {
              dark: '#66b1ff'
            }
          })
        })
      }
    },
    // 获取员工数据列表
    async getcomply() {
      // 加载
      this.loading = true
      // 接口然后结构
      const { total, rows } = await getcomplyi(this.page)
      // 总数给到上面data的total
      this.page.total = total
      // 数据给到上面data的list
      this.list = rows
      // 然后把加载状态改为false
      this.loading = false
    },
    changePage(newPage) {
      // 更新页码配置
      this.page.page = newPage
      // 更新数据
      this.getcomply()
    },
    // 格式化返回的值会替换原来显示的1和2 就是porp哪里的
    formtEmp(row, col, cell, index) {
      // obj 是查找里面的现有数据
      const obj = EnumEmployou.hireType.find(item => Number(item.id) === Number(cell))
      // 然后三元
      return obj ? obj.value : '未知形式'
    },
    async deleteEmployee(id) {
      try {
        // 确定删除员工？
        await this.$confirm(this.$t('confirmDel'))
        // 调用数据
        await delEmployee(id)
        // 删除成功
        this.$message.success('删除成功')
        if (this.list.length === 1 && this.page.page > 1) {
          this.page.page--
        }
        // 刷新数据
        this.getcomply()
      } catch (error) {
        console.log(error)
      }
    },
    async exportExel() {
      // 导出获取所有员工数据
      const { rows } = await getcomplyi({ page: 1, size: this.page.total })
      console.log(rows)
      // 自己定义一个英文名字
      const headers = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 然后map出去给到变量
      const newData = rows.map(user => {
        return this.js2en(user, headers)
      })
      // console.log(newData)
      // 然后把上面headers的数组的key值给到新变量
      const header = Object.keys(headers)
      // console.log(header)

      // excel生成
      const { export_json_to_excel } = await import('@/vendor/Export2Excel')
      export_json_to_excel({
        header,
        data: newData

      })
    },
    // 定义一个方法，用到上面就是封装了
    // 接收两个数据user，headers
    js2en(user, headers) {
      console.log(user)
      // 定义一个空数组接收返回的res
      const res = []
      // 遍历上面的数组
      for (const key in headers) {
        // 拿到key给到新变量
        const en = headers[key]
        // console.log(en)
        // 然后在给到新数组
        // console.log(user[en])
        //  user[en]拿到user里面key对应的value值
        let value = user[en]
        // 如果是聘用形式
        if (en === 'formOfEmployment') {
          const obj = EnumEmployou.hireType.find(item => item.id === value)
          value = obj ? obj.value : '未知形式'
        }
        // 如果是时间
        if (en === 'timeOfEntry' || en === 'correctionTime') {
          value = formatDate(value)
        }
        res.push(value)
      }
      // console.log(res)
      return res
    }
  }
}
</script>

<style lang='scss' scoped>
.avatar{
  width: 200px;
  height: 130px;
  object-fit: contain;
}
</style>
